package com.ep.thirdPlatformProject.system.util;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;

import java.util.List;

@Component
public class WebclientUtil {
    private final WebClient webClient;

    public WebclientUtil(WebClient.Builder webClientBuilder) {
        this.webClient = webClientBuilder.
                build();
    }


    /**
     * get方法
     *
     * @param url          url
     * @param responseType 响应类型
     * @return T
     */
    public <T> T get(String url, Class<T> responseType) {
        return webClient.get().
                uri(url).
                accept(MediaType.APPLICATION_JSON).
                retrieve().
                bodyToMono(responseType).
                block();
    }

    /**
     * get多条数据
     *
     * @param url          url
     * @param responseType 响应类型
     * @return T
     */
    public <T> List<T> list(String url, Class<T> responseType) {
        return webClient.get().
                uri(url).
                accept(MediaType.APPLICATION_JSON).
                retrieve().
                bodyToFlux(responseType).collectList().block();
    }

    /**
     * post方法
     *
     * @param url          url
     * @param responseType 响应类型
     * @return T
     */
    public <T> T post(String url, Object requestBody, Class<T> responseType) {
        return webClient.post()
                .uri(url)
                .header("Content-Type", MediaType.APPLICATION_JSON_VALUE)
                .bodyValue(requestBody)
                .accept(MediaType.APPLICATION_JSON)
                .retrieve()
                .bodyToMono(responseType)
                .block();
    }

    /**
     * put方法
     *
     * @param url          url
     * @param responseType 响应类型
     * @return T
     */
    public <T> T put(String url, Object requestBody, Class<T> responseType) {
        return webClient.put().
                uri(url).
                contentType(MediaType.APPLICATION_JSON).
                bodyValue(requestBody).
                accept(MediaType.APPLICATION_JSON).
                retrieve().
                bodyToMono(responseType).
                block();
    }

    /**
     * 删除方法
     *
     * @param url          url
     * @param responseType 响应类型
     * @return T
     */
    public <T> T delete(String url, Class<T> responseType) {
        return webClient.delete().
                uri(url).
                accept(MediaType.APPLICATION_JSON).
                retrieve().
                bodyToMono(responseType).
                block();
    }


}
